<template>
  <div class="management-container">
    <!-- 顶部标题栏（统一为白底卡片风格） -->
    <div class="header-bar bg-white border border-gray-200 rounded-lg shadow-sm mx-6 my-4 px-4 h-16 flex items-center">
      <div class="header-content w-full flex items-center justify-between">
        <h1 class="header-title text-gray-800">Playwright 自动化测试管理平台</h1>
        <div class="header-actions">
          <el-button type="primary" size="small" class="premium-button primary-button h-10">用户设置</el-button>
        </div>
      </div>
    </div>

    <div class="main-layout px-6 pb-6">
      <!-- 左侧导航栏 -->
      <div class="sidebar bg-white border border-gray-200 rounded-lg shadow-sm text-gray-800">
        <div class="sidebar-header">
          <h2 class="sidebar-title">测试管理</h2>
        </div>
        <nav class="sidebar-nav">
          <div 
            v-for="item in menuItems" 
            :key="item.key"
            class="nav-item"
            :class="{ active: activeMenu === item.key }"
            @click="switchMenu(item.key)"
          >
            <span class="nav-bullet"></span>
            <span class="nav-text">{{ item.name }}</span>
          </div>
        </nav>
      </div>

      <!-- 右侧内容区 -->
      <div class="content-area">
        <!-- 项目管理 -->
        <div v-if="activeMenu === 'projects'" class="content-panel">
          <div class="panel-header">
            <h3 class="panel-title">项目管理</h3>
          </div>
          
          <!-- 搜索区域 -->
          <div class="search-section bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
            <div class="search-row">
              <div class="search-item">
                <label class="search-label">项目名称:</label>
                <el-input 
                  v-model="projectSearch.name" 
                  placeholder="请输入项目名称"
                  class="search-input"
                />
              </div>
              <div class="search-actions">
                <el-button type="primary" class="premium-button primary-button h-10 text-sm font-medium" @click="searchProjects">查询</el-button>
                <el-button class="premium-button white-button h-10 text-sm font-medium" @click="resetProjectSearch">重置</el-button>
                <el-button type="success" class="premium-button success-button h-10 text-sm font-medium" @click="showAddProjectDialog">新增</el-button>
              </div>
            </div>
          </div>

          <!-- 数据表格 -->
          <div class="table-section bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
            <el-table 
              :data="projects" 
              v-loading="projectLoading"
              stripe
              style="width: 100%"
            >
              <el-table-column prop="name" label="项目名称" min-width="200" />
              <el-table-column prop="description" label="项目描述" min-width="300" />
              <el-table-column prop="created_at" label="创建时间" width="180" />
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button size="small" class="premium-button white-button text-xs" @click="editProject(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" class="premium-button h-8 text-xs" @click="deleteProject(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination
            v-if="projectTotal > 0"
            class="mt-4 text-right"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="projectTotal"
            :page-size="projectSize"
            v-model:current-page="projectPage"
            @current-change="onProjectPageChange"
            @size-change="onProjectSizeChange"
            :page-sizes="[10,20,30,50]"
          />
        </div>

        <!-- 脚本管理 -->
        <div v-if="activeMenu === 'scripts'" class="content-panel">
          <div class="panel-header">
            <h3 class="panel-title">脚本管理</h3>
          </div>
          
          <!-- 搜索区域 -->
          <div class="search-section bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
            <div class="search-row">
              <div class="search-item">
                <label class="search-label">所属项目:</label>
                <el-select 
                  v-model="scriptSearch.project_id" 
                  placeholder="请选择项目"
                  class="search-input"
                  clearable
                >
                  <el-option 
                    v-for="project in projects" 
                    :key="project.id" 
                    :label="project.name" 
                    :value="project.id"
                  />
                </el-select>
              </div>
              <div class="search-item">
                <label class="search-label">脚本名称:</label>
                <el-input 
                  v-model="scriptSearch.name" 
                  placeholder="请输入脚本名称"
                  class="search-input"
                />
              </div>
              <div class="search-actions">
                <el-button type="primary" class="premium-button primary-button h-10 text-sm font-medium" @click="searchScripts">查询</el-button>
                <el-button class="premium-button white-button h-10 text-sm font-medium" @click="resetScriptSearch">重置</el-button>
                <el-button type="success" class="premium-button success-button h-10 text-sm font-medium" @click="showAddScriptDialog">新增</el-button>
              </div>
            </div>
          </div>

          <!-- 数据表格 -->
          <div class="table-section bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
            <el-table 
              :data="scripts" 
              v-loading="scriptLoading"
              stripe
              style="width: 100%"
            >
              <el-table-column prop="name" label="脚本名称" min-width="200" />
              <el-table-column prop="project_name" label="所属项目" min-width="150" />
              <el-table-column prop="description" label="脚本描述" min-width="250" />
              <el-table-column prop="created_at" label="创建时间" width="180" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" class="premium-button white-button text-xs" @click="viewScript(scope.row)">查看</el-button>
                  <el-button size="small" class="premium-button white-button text-xs" @click="editScript(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" class="premium-button h-8 text-xs" @click="deleteScript(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination
            v-if="scriptsTotal > 0"
            class="mt-4 text-right"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="scriptsTotal"
            :page-size="scriptsSize"
            :current-page="scriptsPage"
            @current-change="onScriptsPageChange"
            @size-change="onScriptsSizeChange"
            :page-sizes="[10,20,30,50]"
          />
        </div>

        <!-- 任务管理 -->
        <div v-if="activeMenu === 'tasks'" class="content-panel">
          <div class="panel-header">
            <h3 class="panel-title">任务管理</h3>
          </div>
          
          <!-- 搜索区域 -->
          <div class="search-section bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
            <div class="search-row">
              <div class="search-item">
                <label class="search-label">所属项目:</label>
                <el-select 
                  v-model="taskSearch.project_id" 
                  placeholder="请选择项目"
                  class="search-input"
                  clearable
                >
                  <el-option 
                    v-for="project in projects" 
                    :key="project.id" 
                    :label="project.name" 
                    :value="project.id"
                  />
                </el-select>
              </div>
              <div class="search-item">
                <label class="search-label">脚本名称:</label>
                <el-select 
                  v-model="taskSearch.script_id" 
                  placeholder="请选择脚本"
                  class="search-input"
                  clearable
                >
                  <el-option 
                    v-for="script in scripts" 
                    :key="script.id" 
                    :label="script.name" 
                    :value="script.id"
                  />
                </el-select>
              </div>
              <div class="search-item">
                <label class="search-label">执行状态:</label>
                <el-select 
                  v-model="taskSearch.status" 
                  placeholder="请选择状态"
                  class="search-input"
                  clearable
                >
                  <el-option label="运行中" value="running" />
                  <el-option label="成功" value="succeeded" />
                  <el-option label="失败" value="failed" />
                  <el-option label="超时" value="timeout" />
                </el-select>
              </div>
              <div class="search-actions">
                <el-button type="primary" class="premium-button primary-button h-10 text-sm font-medium" @click="searchTasks">查询</el-button>
                <el-button class="premium-button white-button h-10 text-sm font-medium" @click="resetTaskSearch">重置</el-button>
                <el-button type="success" class="premium-button success-button h-10 text-sm font-medium" @click="showAddTaskDialog">新增</el-button>
              </div>
            </div>
          </div>

          <!-- 数据表格 -->
          <div class="table-section bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
            <el-table 
              :data="tasks" 
              v-loading="taskLoading"
              stripe
              style="width: 100%"
            >
              <el-table-column prop="script_name" label="脚本名称" min-width="150" />
              <el-table-column prop="project_name" label="所属项目" min-width="120" />
              <el-table-column prop="status" label="执行状态" width="100">
                <template #default="scope">
                  <el-tag 
                    :type="getStatusType(scope.row.status)"
                    size="small"
                  >
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="execution_start_time" label="开始时间" width="180" />
              <el-table-column prop="execution_end_time" label="结束时间" width="180" />
              <el-table-column prop="duration_seconds" label="执行时长(秒)" width="120" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button size="small" class="premium-button white-button text-xs" @click="viewTask(scope.row)">查看</el-button>
                  <el-button 
                    size="small" 
                    type="warning" 
                    v-if="scope.row.status === 'running'"
                    class="premium-button h-8 text-xs"
                    @click="stopTask(scope.row)"
                  >
                    停止
                  </el-button>
                  <el-button size="small" type="danger" class="premium-button h-8 text-xs" @click="deleteTask(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination
            v-if="taskTotal > 0"
            class="mt-4 text-right"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="taskTotal"
            :page-size="taskSize"
            :current-page="taskPage"
            @current-change="onTaskPageChange"
            @size-change="onTaskSizeChange"
            :page-sizes="[10,20,30,50]"
          />
        </div>
      </div>
    </div>

    <!-- 项目新增/编辑对话框 -->
    <el-dialog 
      v-model="projectDialogVisible" 
      :title="projectDialogTitle"
      width="600px"
    >
      <el-form :model="projectForm" :rules="projectRules" ref="projectFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input 
            v-model="projectForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入项目描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button class="premium-button white-button" @click="projectDialogVisible = false">取消</el-button>
        <el-button type="primary" class="premium-button primary-button" @click="saveProject">确定</el-button>
      </template>
    </el-dialog>

    <!-- 脚本新增/编辑对话框 -->
    <el-dialog 
      v-model="scriptDialogVisible" 
      :title="scriptDialogTitle"
      width="600px"
    >
      <el-form :model="scriptForm" :rules="scriptRules" ref="scriptFormRef" label-width="100px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="scriptForm.project_id" placeholder="请选择项目" style="width: 100%">
            <el-option 
              v-for="project in projects" 
              :key="project.id" 
              :label="project.name" 
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="脚本名称" prop="name">
          <el-input v-model="scriptForm.name" placeholder="请输入脚本名称" />
        </el-form-item>
        <el-form-item label="脚本描述" prop="description">
          <el-input 
            v-model="scriptForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入脚本描述" 
          />
        </el-form-item>
        <!-- 编辑模式下显示代码输入框 -->
        <el-form-item v-if="scriptForm.id" label="脚本代码">
          <el-input 
            v-model="scriptForm.code" 
            type="textarea" 
            :rows="10"
            placeholder="请输入Playwright脚本代码" 
          />
        </el-form-item>
        <!-- 新增模式下显示提示信息 -->
        <el-alert
          v-if="!scriptForm.id"
          title="保存后可在脚本列表中点击编辑按钮进入脚本编辑页面"
          type="info"
          :closable="false"
          style="margin-top: 10px"
        />
      </el-form>
      <template #footer>
        <el-button class="premium-button white-button" @click="scriptDialogVisible = false">取消</el-button>
        <el-button type="primary" class="premium-button primary-button" @click="saveScript">确定</el-button>
      </template>
    </el-dialog>

    <!-- 任务新增对话框 -->
    <el-dialog 
      v-model="taskDialogVisible" 
      title="新增执行任务"
      width="600px"
    >
      <el-form :model="taskForm" :rules="taskRules" ref="taskFormRef" label-width="100px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="taskForm.project_id" placeholder="请选择项目" style="width: 100%" @change="onProjectChange">
            <el-option 
              v-for="project in projects" 
              :key="project.id" 
              :label="project.name" 
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行脚本" prop="script_id">
          <el-select v-model="taskForm.script_id" placeholder="请选择脚本" style="width: 100%">
            <el-option 
              v-for="script in filteredScripts" 
              :key="script.id" 
              :label="script.name" 
              :value="script.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button class="premium-button white-button" @click="taskDialogVisible = false">取消</el-button>
        <el-button type="primary" class="premium-button primary-button" @click="saveTask">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { managementApiService } from '../services/managementApiService.js'

// 路由
const router = useRouter()

// 响应式数据
const activeMenu = ref('projects')

// 菜单项
const menuItems = [
  { key: 'projects', name: '项目管理' },
  { key: 'scripts', name: '脚本管理' },
  { key: 'tasks', name: '任务管理' }
]

// 项目管理相关
const projects = ref([])
const projectLoading = ref(false)
const projectSearch = reactive({
  name: ''
})
// 分页数据
const projectPage = ref(1)
const projectSize = ref(10)
const projectTotal = ref(0)

// 脚本管理相关
const scripts = ref([])
const scriptLoading = ref(false)
const scriptSearch = reactive({
  project_id: '',
  name: ''
})
// 脚本分页
const scriptsPage = ref(1)
const scriptsSize = ref(10)
const scriptsTotal = ref(0)

// 任务管理相关
const tasks = ref([])
const taskLoading = ref(false)
const taskSearch = reactive({
  project_id: '',
  script_id: '',
  status: ''
})
// 任务分页
const taskPage = ref(1)
const taskSize = ref(10)
const taskTotal = ref(0)

// 对话框相关
const projectDialogVisible = ref(false)
const projectDialogTitle = ref('新增项目')
const projectForm = reactive({
  id: '',
  name: '',
  description: ''
})

const scriptDialogVisible = ref(false)
const scriptDialogTitle = ref('新增脚本')
const scriptForm = reactive({
  id: '',
  project_id: '',
  name: '',
  description: '',
  code: ''
})

const taskDialogVisible = ref(false)
const taskForm = reactive({
  project_id: '',
  script_id: ''
})

// 表单验证规则
const projectRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ]
}

const scriptRules = {
  project_id: [
    { required: true, message: '请选择所属项目', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入脚本名称', trigger: 'blur' }
  ]
}

const taskRules = {
  project_id: [
    { required: true, message: '请选择所属项目', trigger: 'change' }
  ],
  script_id: [
    { required: true, message: '请选择执行脚本', trigger: 'change' }
  ]
}

// 计算属性
const filteredScripts = computed(() => {
  if (!taskForm.project_id) return scripts.value
  return scripts.value.filter(script => script.project_id === taskForm.project_id)
})

// 方法
const switchMenu = async (menuKey) => {
  activeMenu.value = menuKey
  // 切换菜单时加载对应数据
  switch (menuKey) {
    case 'projects':
      loadProjects()
      break
    case 'scripts':
      // 切换到脚本管理时，确保项目列表已加载以便匹配项目名称
      if (projects.value.length === 0) {
        await loadProjects()
      }
      // 重置搜索条件和分页，确保显示所有脚本
      scriptSearch.project_id = ''
      scriptSearch.name = ''
      scriptsPage.value = 1
      loadScripts()
      break
    case 'tasks':
      // 切换到任务管理时，确保项目列表和脚本列表已加载
      if (projects.value.length === 0) {
        await loadProjects()
      }
      if (scripts.value.length === 0) {
        await loadScripts()
      }
      loadTasks()
      break
  }
}

// 项目管理方法
const loadProjects = async () => {
  projectLoading.value = true
  try {
    // 带分页参数 (前端页码从1开始，后端从0开始，需要转换)
    console.log("请求参数为："+JSON.stringify({...projectSearch, page:projectPage.value - 1, size:projectSize.value }))
    const response = await managementApiService.getProjects({...projectSearch, page:projectPage.value - 1, size:projectSize.value })
    // 自动兼容新版和旧版，内容统一 .content 总条数 unified .totalElements
    const rawProjects = response.data.content || []
    // 字段映射：将后端字段名映射为前端期望的字段名
    projects.value = rawProjects.map(project => ({
      id: project.projectId,
      name: project.projectName,
      description: project.projectDescription,
      created_at: project.createdAt || project.created_at || new Date().toLocaleString()
    }))
    projectTotal.value = response.data.totalElements || 0
  } catch (error) {
    console.error('加载项目列表失败:', error)
    ElMessage.error('加载项目列表失败')
    // 使用模拟数据作为fallback
    projects.value = [
      {
        id: '1',
        name: '电商平台测试',
        description: '电商平台自动化测试项目',
        created_at: '2024-01-15 10:30:00'
      },
      {
        id: '2',
        name: '用户管理系统',
        description: '用户管理系统的UI自动化测试',
        created_at: '2024-01-20 14:20:00'
      }
    ]
    projectTotal.value = 2
  } finally {
    projectLoading.value = false
  }
}
const onProjectPageChange = (p) => { projectPage.value=p; loadProjects() }
const onProjectSizeChange = (s) => { projectSize.value=s; projectPage.value=1; loadProjects() }

const searchProjects = () => {
  // 查询时重置到第一页
  projectPage.value = 1
  loadProjects()
}

const resetProjectSearch = () => {
  projectSearch.name = ''
  projectPage.value = 1
  loadProjects()
}

const showAddProjectDialog = () => {
  projectDialogTitle.value = '新增项目'
  projectForm.id = ''
  projectForm.name = ''
  projectForm.description = ''
  projectDialogVisible.value = true
}

const editProject = (row) => {
  projectDialogTitle.value = '编辑项目'
  projectForm.id = row.id
  projectForm.name = row.name
  projectForm.description = row.description
  projectDialogVisible.value = true
}

const saveProject = async () => {
  try {
    if (projectForm.id) {
      // 更新项目
      await managementApiService.updateProject(projectForm.id, {
        projectName: projectForm.name,
        projectDescription: projectForm.description
      })
      ElMessage.success('更新成功')
    } else {
      // 创建项目
      await managementApiService.createProject({
        projectName: projectForm.name,
        projectDescription: projectForm.description
      })
      ElMessage.success('创建成功')
    }
    projectDialogVisible.value = false
    loadProjects()
  } catch (error) {
    console.error('保存项目失败:', error)
    ElMessage.error('保存失败')
  }
}

const deleteProject = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该项目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await managementApiService.deleteProject(row.id)
    ElMessage.success('删除成功')
    loadProjects()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除项目失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 辅助函数：根据项目ID获取项目名称
const getProjectNameById = (projectId) => {
  if (!projectId) return ''
  const project = projects.value.find(p => p.id === projectId || p.id === String(projectId))
  return project ? project.name : ''
}

// 脚本管理方法
const loadScripts = async () => {
  scriptLoading.value = true
  try {
    // 确保项目列表已加载，以便匹配项目名称
    // 如果项目列表为空，先加载项目列表（加载足够多的项目以确保能匹配到）
    if (projects.value.length === 0) {
      // 加载前100个项目，通常足够匹配所有脚本的项目
      const originalSize = projectSize.value
      projectSize.value = 100
      await loadProjects()
      projectSize.value = originalSize
    }
    
    // 构建查询参数，只传递非空的搜索条件
    const queryParams = {
      page: scriptsPage.value - 1,
      size: scriptsSize.value
    }
    
    // 只添加非空的查询条件
    if (scriptSearch.project_id && scriptSearch.project_id.trim()) {
      queryParams.project_id = scriptSearch.project_id.trim()
    }
    if (scriptSearch.name && scriptSearch.name.trim()) {
      queryParams.name = scriptSearch.name.trim()
    }
    
    const response = await managementApiService.getScripts(queryParams)
    const rawScripts = response.data.content || []
    // 字段映射：将后端字段名映射为前端期望的字段名，并根据project_id匹配项目名称
    scripts.value = rawScripts.map(script => {
      const projectId = script.project_id
      // 优先使用后端返回的project_name，如果没有则根据project_id从项目列表中查找
      let projectName = script.project_name
      if (!projectName && projectId) {
        projectName = getProjectNameById(projectId)
      }
      // 如果仍然找不到，显示项目ID作为fallback
      if (!projectName && projectId) {
        projectName = `项目ID: ${projectId}`
      }
      
      return {
        id: script.script_id,
        name: script.script_name,
        project_id: projectId,
        project_name: projectName || '未知项目',
        description: script.script_description,
        created_at: script.created_at || new Date().toLocaleString()
      }
    })
    scriptsTotal.value = response.data.totalElements || 0
  } catch (error) {
    console.error('加载脚本列表失败:', error)
    ElMessage.error('加载脚本列表失败')
    // 使用模拟数据作为fallback
    scripts.value = [
      {
        id: '1',
        project_id: '1',
        name: '登录测试脚本',
        project_name: '电商平台测试',
        description: '用户登录功能测试',
        created_at: '2024-01-16 09:15:00'
      },
      {
        id: '2',
        project_id: '1',
        name: '商品搜索脚本',
        project_name: '电商平台测试',
        description: '商品搜索功能测试',
        created_at: '2024-01-17 11:30:00'
      }
    ]
    scriptsTotal.value = 2
  } finally {
    scriptLoading.value = false
  }
}
const onScriptsPageChange = (p) => { scriptsPage.value = p; loadScripts() }
const onScriptsSizeChange = (s) => { scriptsSize.value = s; scriptsPage.value = 1; loadScripts() }

const searchScripts = () => {
  loadScripts()
}

const resetScriptSearch = () => {
  scriptSearch.project_id = ''
  scriptSearch.name = ''
  loadScripts()
}

const showAddScriptDialog = () => {
  scriptDialogTitle.value = '新增脚本'
  scriptForm.id = ''
  scriptForm.project_id = ''
  scriptForm.name = ''
  scriptForm.description = ''
  scriptForm.code = ''
  scriptDialogVisible.value = true
}

const editScript = (row) => {
  // 编辑脚本时，直接跳转到recorder页面进行录制编辑
  router.push({
    path: '/recorder',
    query: {
      scriptName: row.name
    }
  })
}

const viewScript = (row) => {
  // TODO: 打开脚本查看对话框
  ElMessage.info('查看脚本功能待实现')
}

const saveScript = async () => {
  try {
    if (scriptForm.id) {
      // 编辑模式：更新脚本（包含code）
      await managementApiService.updateScript(scriptForm.id, {
        script_name: scriptForm.name,
        script_description: scriptForm.description,
        script_code: scriptForm.code || ''
      })
      ElMessage.success('更新成功')
      scriptDialogVisible.value = false
      loadScripts()
    } else {
      // 新增模式：创建脚本（code为空字符串），只保存不跳转
      const response = await managementApiService.createScript({
        project_id: scriptForm.project_id,
        script_name: scriptForm.name,
        script_description: scriptForm.description,
        script_code: ''  // code部分传递空字符串
      })
      
      // 关闭对话框
      scriptDialogVisible.value = false
      
      // 显示成功消息
      ElMessage.success('脚本创建成功，可在列表中点击编辑按钮进入编辑页面')
      
      // 刷新脚本列表
      loadScripts()
    }
  } catch (error) {
    console.error('保存脚本失败:', error)
    ElMessage.error('保存失败')
  }
}

const deleteScript = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该脚本吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await managementApiService.deleteScript(row.id)
    ElMessage.success('删除成功')
    loadScripts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除脚本失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 任务管理方法
const loadTasks = async () => {
  taskLoading.value = true
  try {
    const response = await managementApiService.getExecutionResults({ ...taskSearch, page: taskPage.value - 1, size: taskSize.value })
    const rawTasks = response.data.content || []
    // 字段映射：执行结果使用数据库字段名
    tasks.value = rawTasks.map(task => ({
      id: task.id,
      script_id: task.script_id,
      script_name: task.script_name,
      project_name: task.project_name,
      status: task.status,
      execution_start_time: task.execution_start_time,
      execution_end_time: task.execution_end_time,
      duration_seconds: task.duration_seconds
    }))
    taskTotal.value = response.data.totalElements || 0
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败')
    // 使用模拟数据作为fallback
    tasks.value = [
      {
        id: '1',
        script_id: '1',
        script_name: '登录测试脚本',
        project_id: '1',
        project_name: '电商平台测试',
        status: 'succeeded',
        execution_start_time: '2024-01-18 10:00:00',
        execution_end_time: '2024-01-18 10:02:30',
        duration_seconds: 150
      },
      {
        id: '2',
        script_id: '2',
        script_name: '商品搜索脚本',
        project_id: '1',
        project_name: '电商平台测试',
        status: 'running',
        execution_start_time: '2024-01-18 14:30:00',
        execution_end_time: null,
        duration_seconds: null
      }
    ]
    taskTotal.value = 2
  } finally {
    taskLoading.value = false
  }
}
const onTaskPageChange = (p) => { taskPage.value=p; loadTasks() }
const onTaskSizeChange = (s) => { taskSize.value=s; taskPage.value=1; loadTasks() }

const searchTasks = () => {
  loadTasks()
}

const resetTaskSearch = () => {
  taskSearch.project_id = ''
  taskSearch.script_id = ''
  taskSearch.status = ''
  loadTasks()
}

const showAddTaskDialog = () => {
  taskForm.project_id = ''
  taskForm.script_id = ''
  taskDialogVisible.value = true
}

const onProjectChange = () => {
  taskForm.script_id = ''
}

const saveTask = async () => {
  try {
    await managementApiService.executeScript(taskForm.script_id, taskForm.project_id)
    ElMessage.success('任务创建成功')
    taskDialogVisible.value = false
    loadTasks()
  } catch (error) {
    console.error('创建任务失败:', error)
    ElMessage.error('任务创建失败')
  }
}

const viewTask = (row) => {
  // TODO: 打开任务详情对话框
  ElMessage.info('查看任务详情功能待实现')
}

const stopTask = async (row) => {
  try {
    await ElMessageBox.confirm('确定要停止该任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await managementApiService.stopExecution(row.id)
    ElMessage.success('任务已停止')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止任务失败:', error)
      ElMessage.error('停止任务失败')
    }
  }
}

const deleteTask = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该任务记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await managementApiService.deleteExecutionResult(row.id)
    ElMessage.success('删除成功')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除任务失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const getStatusType = (status) => {
  const statusMap = {
    'running': 'warning',
    'succeeded': 'success',
    'failed': 'danger',
    'timeout': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'running': '运行中',
    'succeeded': '成功',
    'failed': '失败',
    'timeout': '超时'
  }
  return statusMap[status] || '未知'
}

// 生命周期
onMounted(() => {
  loadProjects()
})
</script>

<style scoped>
.management-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9fafb; /* bg-gray-50 */
}

.header-bar {
  height: 72px; /* 更沉稳的顶部高度 */
  border: 1px solid rgba(17, 24, 39, 0.06);
  backdrop-filter: saturate(180%) blur(6px);
  -webkit-backdrop-filter: saturate(180%) blur(6px);
}

.header-title {
  font-size: 22px;
  font-weight: 600;
  margin: 0;
}

.main-layout {
  display: flex;
  flex: 1;
  gap: 16px;
  overflow: hidden;
}

.sidebar {
  width: 220px;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(17, 24, 39, 0.06);
  box-shadow: 0 10px 30px rgba(2, 6, 23, 0.04);
  border-radius: 12px;
}

.sidebar-header {
  padding: 16px;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.sidebar-nav {
  flex: 1;
  padding: 8px 6px;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-left: 3px solid transparent;
  border-radius: 10px;
}

.nav-item:hover {
  background-color: #f3f4f6; /* gray-100 */
}

.nav-item.active {
  background-color: #eff6ff; /* blue-50 */
  border-left-color: #3b82f6; /* blue-500 */
  box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.12);
}

.nav-bullet {
  width: 8px;
  height: 8px;
  background: linear-gradient(180deg, #93c5fd, #60a5fa);
  border-radius: 2px;
  margin-right: 12px;
}

.nav-item.active .nav-bullet {
  background-color: #3b82f6; /* blue-500 */
}

.nav-text {
  font-size: 14px;
  font-weight: 500;
}

.content-area {
  flex: 1;
  overflow-y: auto;
}

.content-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-right: 2px;
}

.panel-header {
  margin-bottom: 4px;
}

.panel-title {
  font-size: 20px;
  font-weight: 600;
  color: #111827;
  margin: 0 0 4px 0;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-label {
  font-size: 15px;
  color: #4b5563;
  white-space: nowrap;
  min-width: 80px;
}

.search-input {
  width: 260px;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

/* Premium 按钮样式（与录制页统一） */
.premium-button {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease-out;
  border-width: 2px;
  border-radius: 0.75rem; /* rounded-xl */
  font-weight: 600;
  box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
}

.premium-button::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(to right, transparent, rgba(255,255,255,0.1), transparent);
  transform: skewX(-12deg) translateX(-100%);
  transition: transform 0.7s;
}

.premium-button:hover::before {
  transform: translateX(100%);
}

.primary-button {
  background: linear-gradient(to right, #2563eb, #1d4ed8);
  border-color: #3b82f6;
  color: #fff;
}

.white-button {
  background: #fff;
  border-color: #e5e7eb;
  color: #374151;
}

.white-button:hover {
  transform: scale(1.05);
}

.success-button {
  background: linear-gradient(to right, #16a34a, #15803d);
  border-color: #16a34a;
  color: #fff;
}

/* 表格卡片容器统一阴影与边框 */
.table-section {
  flex: 1;
  border: 1px solid rgba(17, 24, 39, 0.06);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(2, 6, 23, 0.04);
}

/* 表格精细化样式（现代感） */
.table-section :deep(.el-table) {
  --table-font-size: 14px;
}
.table-section :deep(.el-table__header th) {
  background: linear-gradient(180deg, #fafcff 0%, #f4f7ff 100%);
  font-weight: 600;
  color: #111827;
  height: 44px;
  border-bottom: 1px solid #eef2ff;
}
.table-section :deep(.el-table__body td) {
  height: 56px;
  padding-top: 6px;
  padding-bottom: 6px;
  border-bottom: 1px solid #f3f4f6;
}
.table-section :deep(.el-table__body tr:hover>td) {
  background: #f5f9ff !important;
}
.table-section :deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 5;
}
.table-section :deep(.cell) {
  line-height: 1.35;
}

/* 分页区域对齐 */
.content-area :deep(.el-pagination) {
  padding-top: 10px;
}
.content-area :deep(.el-pagination .btn-next),
.content-area :deep(.el-pagination .btn-prev),
.content-area :deep(.el-pagination .el-pager li) {
  height: 36px;
  min-width: 36px;
  line-height: 36px;
  font-size: 14px;
}

/* 输入与选择控件尺寸提升 */
.search-section :deep(.el-input__wrapper),
.search-section :deep(.el-select .el-input__wrapper) {
  height: 40px;
  border-width: 2px;
  border-color: #e5e7eb;
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}
.search-section :deep(.el-input__inner) {
  font-size: 14px;
}

/* 搜索卡片轻微色彩，提升层次感 */
.search-section {
  background: linear-gradient(90deg, #f8fbff 0%, #f5f8ff 100%);
  border: 1px solid rgba(17, 24, 39, 0.06);
  box-shadow: 0 10px 30px rgba(2, 6, 23, 0.04);
  border-radius: 12px;
}

/* 按钮尺寸与层次 */
.search-actions :deep(.el-button) {
  min-height: 40px;
  font-size: 14px;
  border-radius: 10px;
}

/* 侧边菜单颜色与可读性增强 */
.nav-item:hover {
  background-color: #eef2ff;
}
.nav-item.active {
  background-color: #eaf1ff;
}

/* 卡片悬浮轻微提升（大厂风） */
.header-bar,
.search-section,
.table-section {
  transition: box-shadow .2s ease, transform .2s ease;
}
.search-section:hover,
.table-section:hover {
  box-shadow: 0 18px 40px rgba(2,6,23,.08);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    height: auto;
  }

  .search-row {
    flex-direction: column;
    align-items: stretch;
  }

  .search-item {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .search-actions {
    margin-left: 0;
    justify-content: center;
  }
}
</style>
